package Model;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by FreyrWings on 2017/5/20.
 * Database connection
 */

public class DataBase {
    private Context context;
    private DataSource ds;
    private Connection connection;

    /**
     *  initialize the settings
     */
    public DataBase(){
        try{
            context = new InitialContext();
            ds = (DataSource)context.lookup("java:/comp/env/jdbc/blog");
            connection = ds.getConnection();
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     *  a function to execute the statement in sql
     *  @param sql  statement
     */
    public void executeStatement(String sql){
        try {
            Statement statement = connection.createStatement();
            statement.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  a function to retrieve data
     *  @param sql   particular statement for data retrieving
     *  @return      the set of results according to the statement
     */
    public ResultSet retrieveData(String sql){
        ResultSet resultSet = null;
        try {
            Statement statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resultSet;
    }

    /**
     * Close the connection to the database
     */
    public void closeConnection(){
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * Escape the single character
     * @param keyword the word to be escaped
     * @return the escaped String that stands for the character
     */
    public static String escape(char keyword){
        String returnKey = "'||chr(";
        returnKey += Integer.valueOf(keyword);
        returnKey += ")||'";
        return returnKey;
    }

    /**
     * Escape words that used to search
     * @param origin the word to be escaped
     * @return the escaped word
     */
    public static String searchEscape(String origin){
        if(origin == null){
            return "";
        }
        return origin.replaceAll("a","aa").replaceAll("'", escape('\'')).replaceAll("%", "a%").replaceAll("&", escape('&')).replaceAll("_", "a_");
    }

    /**
     * Escape words that used to insert
     * @param origin the word to be escaped
     * @return the escaped word
     */
    public static String insertEscape(String origin){
        if(origin == null){
            return "";
        }
        return origin.replaceAll("'", escape('\''));
    }
}